package com.tongtong.stsuserapi.config;

import com.tongtong.stsuserapi.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity配置类
 * 配置密码编码器、访问控制逻辑
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Autowired
	JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

	@Autowired
	AuthenticationEntryPoint authenticationEntryPoint;
	@Autowired
	AccessDeniedHandler accessDeniedHandler;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
				//关闭csrf
				.csrf().disable()
				//不通过Session获取SecurityContext
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				.authorizeRequests()
				// 对于登录接口 允许匿名访问
				.antMatchers("/sts/user/**").hasAuthority("user")
				.antMatchers("/sts/manager/**").hasAuthority("manager")
				// 除上面外的所有请求全部放行
				.anyRequest().permitAll();

		// 添加过滤器
		http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
		//http.addFilter(ExceptionFilter.class);

		// 配置异常处理器
		http.exceptionHandling()
				.authenticationEntryPoint(authenticationEntryPoint) // 认证异常处理器
				.accessDeniedHandler(accessDeniedHandler); // 授权异常处理器

		// 允许跨域
		http.cors();
	}

	/**
	 * 将AuthenticationManager暴露并注入到IOC容器
	 * 用于自定义认证
	 */
	@Bean
	@Override
	protected AuthenticationManager authenticationManager() throws Exception {
		return super.authenticationManager();
	}
}